import { View } from "@tarojs/components";
import { XmPullRefresh, XmImage, XmNavbar } from "@/components/tool";
import React, { Fragment, useEffect, useRef } from "react";
import { observer } from "mobx-react";
import verification from "@/static/images/verification.png";
import Taro from "@tarojs/taro";
import { orderScanCode } from "@/path/api/common";
import { userStore } from "@/store";
import { XmDialogModal } from "@/components/public";
import { Router } from "@/path/router";
import "./index.scss";
function Index() {
  function checkLogin() {
    if (userStore.userInfo.token) {
      return Promise.resolve(userStore.userInfo)
    } else {
      return userStore.refreshToken()
    }
  }
  function toastMsg(filename: string) {
    const innerAudioContext = Taro.createInnerAudioContext()
    innerAudioContext.src = filename
    innerAudioContext.play()
  }
  function bushiHxy(user) {
    if (user.switch != null && user.switch !== 1) {
      XmDialogModal({
        title: "温馨提示",
        content: "您不是核销员",
        closeable: false,
        hideCancelBtn: true
      }).then(() => {
        Router.toTabbarIndex()
      })
      return Promise.reject()
    } else {
      return Promise.resolve()
    }
  }
  const inited = useRef(false)
  useEffect(() => {
    Taro.eventCenter.on("userinfoGeted", function () {
      inited.current === false && bushiHxy(userStore.userInfo)
      inited.current = true
    })
  }, [])
  function onHexiao() {
    checkLogin().then((user) => {
      return bushiHxy(user)
    }).then(() => {
      return Taro.scanCode({})
    }).then((res) => {
      setTimeout(() => {
        orderScanCode({
          no: res.result
        }).then((res) => {
          toastMsg(res.data.filename)
          XmDialogModal({
            title: "温馨提示",
            content: res.msg,
            hideCancelBtn: true,
          })
        }).catch((err) => {
          if (err && err.msg && err.data && err.data.filename) {
            toastMsg(err.data.filename)
          }
        })
      }, 600);
    })
  }
  function onHistory() {
    Router.toOrderRecord({ no: "" })
  }
  return <View className="bg-page">
    <XmNavbar title="核销员" fixed={false} hideLeftIcon></XmNavbar>
    <XmPullRefresh className="verification-page" >
      <View className="card">
        <XmImage size="684*492" static src={verification} className="card-img"></XmImage>
        <View className="verification-btn hexiao s-lg-1 f-weight-bold t-center c-white" onClick={onHexiao}>扫码核销</View>
        <View className="verification-btn history s-lg-1 f-weight-bold t-center c-white" onClick={onHistory}>核销记录</View>
      </View>
    </XmPullRefresh>
  </View>
}
const Higher = React.memo(observer(Index));
export default () => <Fragment><Higher /></Fragment>